<?php
session_start();
require_once '../utils/validUtils.php';
require_once '../utils/Response.php';
require_once '../config/dbConfig.php';
global $conn;
connectDB();

$username = $_POST['username'];
$password = $_POST['password'];
$errors = [];

if (!validate_username($username)) {
    $errors['username'] = '用户名必须以字母开头';
}

if (!validate_password($password)) {
    $errors['password'] = '密码长度必须在6-8个字符之间';
}

if (!empty($errors)) {
    Response::error('验证失败', $errors)->send();
}

$stmt = $conn->prepare("SELECT * FROM user WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    Response::error('登录失败', ['auth' => '用户名或密码错误'])->send();
}

$user = $result->fetch_assoc();
if ($password === $user['password']) {  
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    
    Response::success('登录成功', [
        'user' => [
            'id' => $user['id'],
            'username' => $user['username']
        ],
//        'session_id' => session_id()
    ])->send();
} else {
    Response::error('登录失败', ['auth' => '用户名或密码错误'])->send();
}

$stmt->close();
$conn->close();

